package com.mingtu.dzpatrol.activity;

import android.content.pm.ApplicationInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapException;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.AMapNaviViewListener;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.NaviSetting;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.model.AMapCalcRouteResult;
import com.amap.api.navi.model.AMapLaneInfo;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviRouteNotifyData;
import com.amap.api.navi.model.AMapNaviTrafficFacilityInfo;
import com.amap.api.navi.model.AMapServiceAreaInfo;
import com.amap.api.navi.model.AimLessModeCongestionInfo;
import com.amap.api.navi.model.AimLessModeStat;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.StringUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.base.BaseActivity;
import com.mingtu.dzpatrol.utils.ActivityUtil;
import com.mingtu.dzpatrol.utils.Constant;
import com.mingtu.dzpatrol.utils.MyLogUtil;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.dzpatrol.utils.Constant.MAX_ZOOM;


public class NaviMapActivity extends BaseActivity implements AMapNaviListener, AMapNaviViewListener {
    @BindView(R.id.mapView)
    AMapNaviView mapView;
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;
    private AMap aMap;
    private LatLng location;
    private List<Marker> markerList = new ArrayList<>();
    private boolean isSwitch = false;
    private ImmersionBar immersionBar;
    private double fireLng;
    private double fireLat;
    private String lng;
    private String lat;
    private AMapNavi mAMapNavi;
    private LatLng firLocation;
    private NaviLatLng startPoint;
    private NaviLatLng endPoint;
    private List<NaviLatLng> sList;
    private List<NaviLatLng> eList;
    private int strategy;
    private boolean isFire;
    private int locationNum = 0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_navi_map;
    }

    @Override
    protected void initView() {
        hideHeadView();
        //沉侵式状态栏
        immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);  //状态栏字体是深色，不写默认为亮色
        immersionBar.navigationBarDarkIcon(false);
        immersionBar.init();
    }

    @Override
    protected void initData() {
        setSrlEnableOverScrollDrag(false);
    }

    @Override
    protected void getData() {

    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        try {

            NaviSetting.updatePrivacyShow(context, true, true);
            NaviSetting.updatePrivacyAgree(context, true);
            mAMapNavi = AMapNavi.getInstance(getApplicationContext());
            mAMapNavi.addAMapNaviListener(this);
            mAMapNavi.setUseInnerVoice(true, true);
        } catch (AMapException e) {
            e.printStackTrace();
        }

        mapView = findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT ,此处设置无效
//        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
//        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
//        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        mapView.setAMapNaviViewListener(this);

        AMapNaviViewOptions options = mapView.getViewOptions();
        options.setLayoutVisible(true);
        mapView.setViewOptions(options);

//        String address = SPStaticUtils.getString(SPTools.address);

//
//
//        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
//            location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
//
//            startPoint = new NaviLatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
//
//            //添加Marker
//            MarkerOptions markerOptions = new MarkerOptions()
//                    .position(location)
//                    .zIndex(MAP_INDEX)
//                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
//            Marker marker = aMap.addMarker(markerOptions);
//            markerList.add(marker);
//            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
//        }

        //火情点
        lng = getIntent().getStringExtra("lng");
        lat = getIntent().getStringExtra("lat");
        isFire = getIntent().getBooleanExtra("isFire", true);
        if (!StringUtils.isEmpty(lng) && !StringUtils.isEmpty(lat)) {
            fireLng = Double.parseDouble(lng);
            fireLat = Double.parseDouble(lat);
            firLocation = new LatLng(fireLat, fireLng);
            endPoint = new NaviLatLng(fireLat, fireLng);
            if (isFire) {
                ApplicationInfo appInfo = getApplicationInfo();
                ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
                for (int i = 1; i <= 74; i++) {
                    int resID = getResources().getIdentifier("icon_fire" + i, "mipmap", appInfo.packageName);
                    giflist.add(BitmapDescriptorFactory.fromResource(resID));
                }

                MarkerOptions markerOptions = new MarkerOptions()
                        .position(firLocation)
                        .period(3)
                        .icons(giflist);
                Marker marker = aMap.addMarker(markerOptions);
                markerList.add(marker);
            }

        }

        locationPermissions();

    }

    @OnClick({R.id.iv_switch})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.iv_switch:
                if (isSwitch) {
                    isSwitch = false;
                    aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                    immersionBar.statusBarDarkFont(true);
                    immersionBar.init();
                } else {
                    isSwitch = true;
                    aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 卫星地图模式
                    immersionBar.statusBarDarkFont(false);
                    immersionBar.init();
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        if (aMap != null) {
            mapView.onDestroy();
        }

        if (markerList.size() > 0) {
            for (Marker marker : markerList) {
                marker.remove();
            }
            markerList.clear();
        }

        if (mAMapNavi != null) {
            mAMapNavi.stopNavi();
            mAMapNavi.destroy();
        }

        super.onDestroy();
    }

    @Override
    public void onInitNaviFailure() {

    }

    @Override
    public void onInitNaviSuccess() {


    }

    @Override
    public void onStartNavi(int i) {
    }

    @Override
    public void onTrafficStatusUpdate() {

    }

    @Override
    public void onLocationChange(AMapNaviLocation aMapNaviLocation) {
        locationNum++;
        if (locationNum == 1) {
            startPoint = aMapNaviLocation.getCoord();
            try {
                //再次强调，最后一个参数为true时代表多路径，否则代表单路径
                strategy = mAMapNavi.strategyConvert(true, false, false, false, false);
                sList = new ArrayList<>();
                eList = new ArrayList<>();
                sList.add(startPoint);
                eList.add(endPoint);
                mAMapNavi.calculateDriveRoute(sList, eList, null, strategy);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onGetNavigationText(int i, String s) {

    }

    @Override
    public void onGetNavigationText(String s) {

    }

    @Override
    public void onEndEmulatorNavi() {

    }

    @Override
    public void onArriveDestination() {

    }

    @Override
    public void onCalculateRouteFailure(int i) {

    }

    @Override
    public void onReCalculateRouteForYaw() {

    }

    @Override
    public void onReCalculateRouteForTrafficJam() {

    }

    @Override
    public void onArrivedWayPoint(int i) {

    }

    @Override
    public void onGpsOpenStatus(boolean b) {

    }

    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {


    }

    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapNaviCameraInfos) {

    }

    @Override
    public void updateIntervalCameraInfo(AMapNaviCameraInfo aMapNaviCameraInfo, AMapNaviCameraInfo aMapNaviCameraInfo1, int i) {

    }

    @Override
    public void onServiceAreaUpdate(AMapServiceAreaInfo[] aMapServiceAreaInfos) {

    }

    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {

    }

    @Override
    public void hideCross() {

    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {

    }

    @Override
    public void hideModeCross() {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo[] aMapLaneInfos, byte[] bytes, byte[] bytes1) {

    }

    @Override
    public void showLaneInfo(AMapLaneInfo aMapLaneInfo) {

    }

    @Override
    public void hideLaneInfo() {

    }

    @Override
    public void onCalculateRouteSuccess(int[] ints) {

    }

    @Override
    public void notifyParallelRoad(int i) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo[] aMapNaviTrafficFacilityInfos) {

    }

    @Override
    public void OnUpdateTrafficFacility(AMapNaviTrafficFacilityInfo aMapNaviTrafficFacilityInfo) {

    }

    @Override
    public void updateAimlessModeStatistics(AimLessModeStat aimLessModeStat) {
        int distance = aimLessModeStat.getAimlessModeDistance();
        int time = aimLessModeStat.getAimlessModeTime();

        MyLogUtil.e("testtest", "distance===" + distance);
        MyLogUtil.e("testtest", "time===" + time);

    }

    @Override
    public void updateAimlessModeCongestionInfo(AimLessModeCongestionInfo aimLessModeCongestionInfo) {

    }

    @Override
    public void onPlayRing(int i) {

    }

    @Override
    public void onCalculateRouteSuccess(AMapCalcRouteResult aMapCalcRouteResult) {
        try {
            mAMapNavi.startNavi(NaviType.GPS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCalculateRouteFailure(AMapCalcRouteResult aMapCalcRouteResult) {

    }

    @Override
    public void onNaviRouteNotify(AMapNaviRouteNotifyData aMapNaviRouteNotifyData) {

    }

    @Override
    public void onGpsSignalWeak(boolean b) {

    }

    public void locationPermissions() {
        //为了适配android11，这个权限单独申请。如果申请的权限中包含后台定位权限， 那么这里面则不能包含和定位无关的权限，否则框架会抛出异常，
        // 因为 ACCESS_BACKGROUND_LOCATION 和其他非定位权限定位掺和在一起申请，在 Android 11 上会出现不申请直接被拒绝的情况。
        //也就是说，如果你想获得后台定位权限，必须弹窗两次：
        //第一次，申请普通定位权限的弹窗。
        //第二次，在用户同意了普通定位权限之后，申请 后台定位权限时弹窗。
        //这里也要千万注意，在没有拿到 普通定位权限的时候，直接申请后台定位权限，将不弹窗直接授权失败。
        XXPermissions.with(this)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .permission(Permission.ACCESS_FINE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (permissions.contains(Permission.ACCESS_COARSE_LOCATION) ||
                                permissions.contains(Permission.ACCESS_FINE_LOCATION)) {
                            backgroundPermissions();
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            new XPopup.Builder(ActivityUtils.getTopActivity())
                                    .isDestroyOnDismiss(true)
                                    .dismissOnTouchOutside(true)
                                    .hasShadowBg(true)
                                    .asConfirm(context.getResources().getString(R.string.text_tip), "请手动授予定位权限~",
                                            context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                            new OnConfirmListener() {
                                                @Override
                                                public void onConfirm() {
                                                    XXPermissions.startPermissionActivity(ActivityUtils.getTopActivity(), permissions);
                                                }
                                            }, null, false)
                                    .show();
                        } else {

                        }

                    }
                });
    }

    private void backgroundPermissions() {
        XXPermissions.with(this)
                .permission(Permission.ACCESS_BACKGROUND_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {

                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                    }
                });
    }

    @Override
    public void onNaviSetting() {

    }

    @Override
    public void onNaviCancel() {
        ActivityUtil.removeActivity(this);
    }

    @Override
    public boolean onNaviBackClick() {
        return false;
    }

    @Override
    public void onNaviMapMode(int i) {

    }

    @Override
    public void onNaviTurnClick() {

    }

    @Override
    public void onNextRoadClick() {

    }

    @Override
    public void onScanViewButtonClick() {

    }

    @Override
    public void onLockMap(boolean b) {

    }

    @Override
    public void onNaviViewLoaded() {

    }

    @Override
    public void onMapTypeChanged(int i) {

    }

    @Override
    public void onNaviViewShowMode(int i) {

    }
}